/**
 * FileName: HomeController
 * Author:   秋水浮萍
 * Date:     2020/6/22 0:55
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.crm.crm.controller;

import com.crm.crm.service.SysHomeService;
import com.crm.entity.MyHome;
import com.crm.entity.SysUser;
import com.crm.model.Aim;
import com.crm.model.AimExcel;
import com.crm.model.JsonMessage;
import com.crm.security.AuthUserDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author 秋水浮萍
 * @create 2020/6/22
 * @since 1.0.0
 */
@RestController
@Api(value = "标的日志接口")
@RequestMapping("/home")
public class SysHomeController {

    @Autowired
    private SysHomeService sysHomeService;


    /**
     * 按年度信息查询
     *
     * @param time
     * @return
     */
    @ApiOperation(value = "按年度信息查询")
    @PostMapping("yearAim")
    public JsonMessage allAim(String time) {
        JsonMessage message = new JsonMessage();
        List<Aim> aims = sysHomeService.yearAim(time);
        List<Aim> aimList = sysHomeService.allName();
        for (Aim a : aims
        ) {
            for (Aim al : aimList
            ) {
                if (al.getUserId().equals(a.getUserId()) && a.getDepId() == null) {
                    a.setDepId(al.getDepId());
                    a.setDepName(al.getDepName());
                }
            }
        }
        Calendar cal = Calendar.getInstance();
        String maxTime = String.valueOf(cal.get(Calendar.YEAR));
        String minTime = sysHomeService.minTime();
        if (minTime != null) {

            aims.get(0).setMinTime(minTime.subSequence(0, 4).toString());
            aims.get(0).setMaxTime(maxTime);
        }
        message.setData(aims);
        return message;
    }

    @ApiIgnore
    @PostMapping("homeList")
    public JsonMessage homeList() {
        JsonMessage message = new JsonMessage();
        List<MyHome> list = new ArrayList<>();
        for (int i = 1; i < 7; i++) {
            MyHome home = sysHomeService.homeList(i);
            list.add(home);
        }
        message.setData(list);

        return message;
    }


    public void addAim(Aim aim) {
        aim.setCreateTime(new Date());
        sysHomeService.Aim(aim);
    }

    /**
     * 查询目标
     *
     * @param authentication
     * @return
     */
    @ApiOperation(value = "查询目标")
    @PostMapping("findAim")
    public JsonMessage findAim(Authentication authentication, String userId, String time) {
        JsonMessage message = new JsonMessage();
        AuthUserDetail detail = (AuthUserDetail) authentication.getDetails();
        Aim aim = sysHomeService.findAim(userId, time);
        Aim a = new Aim();
        SysUser user = sysHomeService.user(userId);


        if (aim == null) {

            a.setUserId(userId);
            a.setCreateTime(new Date());
            a.setDepId(user.getDepId());
            a.setYear(time);
            addAim(a);
            aim = sysHomeService.findAim(userId, time);
        }
        aim.setTrueName(user.getTrueName());
        message.setData(aim);
        return message;
    }


    /**
     * 更新目标
     *
     * @param authentication
     * @param
     * @return
     */
    @ApiOperation(value = "更新目标")
    @PostMapping("update")
    public JsonMessage updateAim(Authentication authentication,
                                 int quarter1, int quarter2, int quarter3,
                                 int quarter4, int yr, String depId, String userId, String year) {
        AuthUserDetail detail = (AuthUserDetail) authentication.getDetails();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sysHomeService.updateAim(quarter1, quarter2, quarter3, quarter4, yr, sdf.format(new Date()), depId, userId, year);
        JsonMessage message = new JsonMessage();
        return message;
    }

    /**
     * 查询所有信息
     *
     * @param authentication
     * @return
     */
    @ApiOperation(value = "查询所有信息")
    @PostMapping("allAim")
    public JsonMessage timeAim(Authentication authentication) {
        AuthUserDetail detail = (AuthUserDetail) authentication.getDetails();
        List<Aim> aims = sysHomeService.allAim();
        List<Aim> aimList = sysHomeService.allName();
        for (Aim a : aims
        ) {
            for (Aim al : aimList
            ) {
                if (al.getUserId().equals(a.getUserId()) && a.getDepId() == null) {
                    a.setDepId(al.getDepId());
                    a.setDepName(al.getDepName());
                }
            }
        }
        JsonMessage message = new JsonMessage();
        String minTime = sysHomeService.minTime();
        Calendar cal = Calendar.getInstance();
        String maxTime = String.valueOf(cal.get(Calendar.YEAR));
        aims.get(0).setMinTime(minTime);
        aims.get(0).setMaxTime(maxTime);
        message.setData(aims);
        return message;
    }

    @ApiOperation(value = "导出")
    @RequestMapping("export")
    public ResponseEntity<byte[]> export(String time) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        XSSFWorkbook hssfWorkbook = new XSSFWorkbook();
        XSSFSheet sheet1 = hssfWorkbook.createSheet("Sheet1");
        List<AimExcel> excels = convertData(time);
        String[] headerList1 = {"序号", "部门", "姓名", "第一季度目标", "第二季度目标", "第三季度目标", "第四季度目标", "年度目标", "第一季度客户数量", "第二季度客户数量", "第三季度客户数量", "第四季度客户数量", "第一季度伙伴数量", "第二季度伙伴数量", "第三季度伙伴数量", "第四季度伙伴数量"};
        XSSFRow row = sheet1.createRow(0);
        for (int i = 0; i < headerList1.length; i++) {
            row.createCell(i).setCellValue(headerList1[i]);
        }
        int i = 0;
        for (AimExcel stat : excels) {
            int j = 0;
            XSSFRow row1 = sheet1.createRow(++i);
            row1.createCell(j++).setCellValue(i);
            row1.createCell(j++).setCellValue(stat.getDepName());
            row1.createCell(j++).setCellValue(stat.getTrueName());
            row1.createCell(j++).setCellValue(stat.getQuarter1());
            row1.createCell(j++).setCellValue(stat.getQuarter2());
            row1.createCell(j++).setCellValue(stat.getQuarter3());
            row1.createCell(j++).setCellValue(stat.getQuarter4());
            row1.createCell(j++).setCellValue(stat.getYr());
            row1.createCell(j++).setCellValue(stat.getQuantity1());
            row1.createCell(j++).setCellValue(stat.getQuantity2());
            row1.createCell(j++).setCellValue(stat.getQuantity3());
            row1.createCell(j++).setCellValue(stat.getQuantity4());
            row1.createCell(j++).setCellValue(stat.getPartner1());
            row1.createCell(j++).setCellValue(stat.getPartner2());
            row1.createCell(j++).setCellValue(stat.getPartner3());
            row1.createCell(j++).setCellValue(stat.getPartner4());
        }
        try {
            hssfWorkbook.write(os);
            hssfWorkbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        HttpHeaders headers = new HttpHeaders();
        // headers.add("Content-Type", "application/octet-stream;charset=utf-8");
        headers.add("Content-Type", "application/vnd.ms-excel;charset=UTF-8");
        headers.add("Connection", "close");
        headers.add("Accept-Ranges", "bytes");
        headers.add("Access-Control-Expose-Headers", "Content-Disposition");
        String myFileName = URLEncoder.encode("汇总.xlsx", Charset.forName("utf-8"));
        headers.add("Content-Disposition", "attachment;filename=" + myFileName);
        //   + new String( "汇总.xlsx".getBytes(Charset.forName("UTF-8")), Charset.forName("ISO-8859-1")));
        return ResponseEntity
                .ok()
                .headers(headers)
                //.contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(os.toByteArray());
    }


    public List<AimExcel> convertData(String time) {
        List<AimExcel> excels = new ArrayList<>();

        //所有人信息
        List<Aim> aims = sysHomeService.yearAim(time);
        List<Aim> aimList = sysHomeService.allName();

        for (Aim a : aims) {
            for (Aim al : aimList) {
                if (al.getUserId().equals(a.getUserId()) && a.getDepId() == null) {
                    a.setDepId(al.getDepId());
                    a.setDepName(al.getDepName());
                }
            }
        }
        //所有有季度录入客户数
        List<AimExcel> all = sysHomeService.allInfo();
        for (AimExcel a : all) {
            for (Aim al : aimList) {
                if (al.getUserId().equals(a.getUserId()) && a.getDepId() == null) {
                    a.setDepId(al.getDepId());
                    a.setDepName(al.getDepName());
                }
            }
        }
        List<AimExcel> ae1 = sysHomeService.quarter(1, time);
        List<AimExcel> ae2 = sysHomeService.quarter(2, time);
        List<AimExcel> ae3 = sysHomeService.quarter(3, time);
        List<AimExcel> ae4 = sysHomeService.quarter(4, time);
        for (int i = 0; i < all.size(); i++) {
            if (ae1 == null) {
                ae1.add(all.get(i));
            }
            if (ae2 == null) {
                ae2.add(all.get(i));
            }
            if (ae3 == null) {
                ae3.add(all.get(i));
            }
            if (ae4 == null) {
                ae4.add(all.get(i));
            }

        }
        for (int i = 0; i < all.size(); i++) {
            for (int j = 0; j < ae1.size(); j++) {
                if (ae1.get(j).getUserId().equals(all.get(i).getUserId())) {
                    all.get(i).setQuantity1(ae1.get(j).getQuantity1());
                    all.get(i).setPartner1(ae1.get(j).getPartner1());
                }
            }
            for (int j = 0; j < ae2.size(); j++) {
                if (ae2.get(j).getUserId().equals(all.get(i).getUserId())) {
                    all.get(i).setQuantity2(ae2.get(j).getQuantity1());
                    all.get(i).setPartner2(ae2.get(j).getPartner1());
                }
            }
            for (int j = 0; j < ae3.size(); j++) {
                if (ae3.get(j).getUserId().equals(all.get(i).getUserId())) {
                    all.get(i).setQuantity3(ae3.get(j).getQuantity1());
                    all.get(i).setPartner3(ae3.get(j).getPartner1());
                }
            }
            for (int j = 0; j < ae4.size(); j++) {
                if (ae4.get(j).getUserId().equals(all.get(i).getUserId())) {
                    all.get(i).setQuantity4(ae4.get(j).getQuantity1());
                    all.get(i).setPartner4(ae4.get(j).getPartner1());
                }
            }

        }
        for (int i = 0; i < aims.size(); i++) {
            for (int j = 0; j < all.size(); j++) {
                if (all.get(j).getUserId().equals(aims.get(i).getUserId())) {
                    excels.add(new AimExcel(all.get(j).getDepId(), aims.get(i).getDepName(), aims.get(i).getTrueName(), aims.get(i).getQuarter1(), aims.get(i).getQuarter2(), aims.get(i).getQuarter3(), aims.get(i).getQuarter4(), aims.get(i).getYr(),
                            all.get(j).getQuantity1(), all.get(j).getQuantity2(), all.get(j).getQuantity3(), all.get(j).getQuantity4(),
                            all.get(j).getPartner1(), all.get(j).getPartner2(), all.get(j).getPartner3(), all.get(j).getPartner4()));
                }
            }
        }
        Collections.sort(excels, new Comparator<AimExcel>() {
            @Override
            public int compare(AimExcel o1, AimExcel o2) {
                return o1.getDepId().compareTo(o2.getDepId());
            }
        });
        return excels;
    }


}
